package com.javastudy.thread;

public class WaitNotifyTest {

    public static Object baozi = null;

    public static void main(String[] args) throws InterruptedException {
        WaitNotifyTest test = new WaitNotifyTest();
//        test.WaitNotifyTest();//正常情况
        test.WaitNotifyTestDeadLock();//顺序调用导致的死锁

    }

    public void WaitNotifyTest() throws InterruptedException {
        Thread thread = new Thread(() -> {
            System.out.println("1.出来买包子");
            while(baozi == null){
                System.out.println("2.没有包子，进入等待");
                try {
                    synchronized (this){
                        this.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("3.买到包子回家");
        });
        thread.start();
        Thread.sleep(3000);//3秒后生产出一个包子
        System.out.println("4.通知来买包子");
        synchronized (this){
            this.notifyAll();
        }
    }

    public void WaitNotifyTestDeadLock() throws InterruptedException {
        Thread thread = new Thread(() -> {
            System.out.println("1.出来买包子");
            while(baozi == null){
                System.out.println("2.没有包子，进入等待");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    synchronized (this){
                        this.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("3.买到包子回家");
        });
        thread.start();
        Thread.sleep(3000);//3秒后生产出一个包子
        System.out.println("4.通知来买包子");
        synchronized (this){
            this.notify();
        }
    }
}
